package com.weilx959.spt.plugin.e2sp.utils.sql.deparser;

import com.weilx959.spt.core.utils.Assert;
import com.weilx959.spt.plugin.e2sp.model.statement.DeleteStatement;
import com.weilx959.spt.plugin.e2sp.model.statement.Statement;
import com.weilx959.spt.plugin.e2sp.utils.sql.SqlUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.delete.Delete;

import java.util.HashMap;
import java.util.Map;

/**
 * delete sql语句解析器
 *
 * @author weilx
 * @since 2024-07-02
 */
@Slf4j
public class DeleteSQLDeParser implements SQLDeParser<Delete> {
    @Override
    public Statement deParse(Delete delete) {
        Assert.notNull(delete, "Delete statement must not be null");
        Assert.notNull(delete.getWhere(), "Delete statement must have a where expression");
        DeleteStatement deleteStatement = new DeleteStatement();
        deleteStatement.setSchema(delete.getTable().getSchemaName());
        deleteStatement.setTableName(delete.getTable().getName());
        Map<String, Object> parameters = new HashMap<>();
        SqlUtil.parseWhereExpression(delete.getWhere(), parameters);
        log.info("Delete SQL: {}, parameters: {}", delete, parameters);
        deleteStatement.setKeys(parameters.keySet().stream().toList());
        deleteStatement.setValues(parameters.values().stream().toList());
        deleteStatement.setDelete(delete);
        return deleteStatement;
    }
}
